package com.nostop.common;

import com.nostop.util.JsonMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@Slf4j
public class HttpInterceprot extends HandlerInterceptorAdapter {
    //还要在spring-servlet.xml把这个HttpInterceprot注册到spring容器中
    private static final String START_TIME = "requestStartTime";

    @Override//请求前
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String url = request.getRequestURL().toString();
        Map parameterMap = request.getParameterMap();
        log.info("request preHandle url:{},params{}",url, JsonMapper.obj2String(parameterMap));
        long start = System.currentTimeMillis();
        request.setAttribute(START_TIME,start);
        //return super.preHandle(request, response, handler);
        //放行
        return true;
    }

    @Override//请求后
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        String url = request.getRequestURL().toString();
        Map parameterMap = request.getParameterMap();
        log.info("request postHandle url:{},params{}",url, JsonMapper.obj2String(parameterMap));
        long start = (long) request.getAttribute(START_TIME);
        long end = System.currentTimeMillis();
        log.info("request need time url:{},cost:{}",url,end-start);
        super.postHandle(request, response, handler, modelAndView);
        removeThreadLocalInfo();
    }

    @Override//请求结束之后，会包括请求异常的情况下也会执行，是百分百触发的
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        String url = request.getRequestURL().toString();
        Map parameterMap = request.getParameterMap();
        log.info("request afterCompletion url:{},params{}",url, JsonMapper.obj2String(parameterMap));
        super.afterCompletion(request, response, handler, ex);
        removeThreadLocalInfo();
    }

    public void removeThreadLocalInfo() {
        RequestHolder.remove();
    }



}
